package com.zhida.smartcontrol.pagehome;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.jay.tools.base.BaseDialogFragment;
import com.jay.tools.base.BaseFragment;
import com.jay.tools.recycler.OnItemClick;
import com.jay.tools.utils.DimenUtils;
import com.jay.tools.utils.EventBusUtils;
import com.jay.tools.utils.LogUtil;
import com.jay.tools.utils.SharedUtil;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.common.Const;
import com.zhida.smartcontrol.common.Keys;
import com.zhida.smartcontrol.common.bean.LampBean;
import com.zhida.smartcontrol.common.mapsel.MapSelPresenter;
import com.zhida.smartcontrol.dialog.devicelistdialog.DeviceListDialogFragment;
import com.zhida.smartcontrol.dialog.kgsjdialog.KgsjDialogFragment;
import com.zhida.smartcontrol.launch.bottom.BottomItemFragment;
import com.zhida.smartcontrol.pagectrl.ProjectListBean;
import com.zhida.smartcontrol.pagectrl.projectdetail.ProjectDetailFragment;
import com.zhida.smartcontrol.pagectrl.projectdetail.warning.WarningBean;
import com.zhida.smartcontrol.pagehome.hdimmerdialog.HDimmerDialogFragment;
import com.zhida.smartcontrol.pagehome.scan.ScanFragment;
import com.zhida.smartcontrol.pagehome.search.SearchFragment;
import com.zhida.smartcontrol.pop.DandengPop;
import com.zhida.smartcontrol.pop.JkqPop;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * author: tanjianpei
 * date: 2019/10/8 008 15:34
 * description: 首页
 */
public class PageHomeFragment extends BottomItemFragment<PageHomeContract.View, PageHomePresenter> implements PageHomeContract.View {
    @BindView(R.id.view)
    View mRoot;
    @BindView(R.id.bmapView)
    TextureMapView mMapView;
    @BindView(R.id.tv_search)
    TextView mTvSearch;
    @BindView(R.id.ll_sao)
    LinearLayout mLLSao;
    @BindView(R.id.ll_switch_project)
    LinearLayout mLLSwitch;
    @BindView(R.id.ll_gz)
    RelativeLayout mLLGz;
    @BindView(R.id.tv_yichang_num)
    TextView mTvYichangNum;

    private String mId;
    private BaiduMap mBaiduMap;
    private JkqPop mPopJkq;
    private DandengPop mPopDandeng;
private LocationClient mLocationClient;
    @Override
    protected Object getLayout() {
        return R.layout.fragment_page_home;
    }

    @Override
    protected void initLazy(Bundle savedInstanceState) {
        initBaiduMap(mMapView.getMap());

        mPresenter.requestProjectList();

        EventBusUtils.register(this);

        String string = SharedUtil.getString(Keys.INPUT_USER, "");
        if (string.equals("admin")) {
            mLLSao.setVisibility(View.VISIBLE);
            mLLSwitch.setVisibility(View.VISIBLE);
        } else {
            mLLSao.setVisibility(View.GONE);
            mLLSwitch.setVisibility(View.GONE);
        }

    }

    public void initBaiduMap(BaiduMap baiduMap) {
        mBaiduMap = mMapView.getMap();
        // 设置地图缩放级别
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(15.0f);

        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        //定位初始化
        mLocationClient = new LocationClient(getContext());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        mLocationClient.setLocOption(option);

        mLocationClient.registerLocationListener(new MyLocationListener());
        //开启地图定位图层
        mLocationClient.start();
        mBaiduMap.setMyLocationEnabled(true);
    }
    private CircleOptions ooCircle;
    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null) {
                return;
            }

            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

            ooCircle = new CircleOptions().fillColor(0x303862FF)
                    .center(latLng)
                    .radius(DimenUtils.dp2px(getContext(), 96));
            mBaiduMap.addOverlay(ooCircle);

            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_location_dot_blue);

            OverlayOptions option = new MarkerOptions().position(latLng).icon(bitmap);
            mBaiduMap.addOverlay(option);
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(latLng));
        }
    }

    @Override
    public void showProjectId(String id) {
        mId = id;
        mPresenter.requestByProjectAndKeyWord(id);
        mPresenter.requestWarning(id);
    }

    @Override
    public void showList(List<ProjectResultBean> resultBeans) {
        setOverLay(resultBeans, null);

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                LatLng position = marker.getPosition();

                ProjectResultBean bean = setOverLay(resultBeans, position);
                if (null != bean)
                    mPresenter.requestLampData(bean.getId());

                ooCircle.center(position);
                mBaiduMap.addOverlay(ooCircle);
                return false;
            }
        });
    }

    /**
     * 设置坐标点图标 ,获取当前点击的设备
     */
    private ProjectResultBean setOverLay(List<ProjectResultBean> resultBeans, LatLng position) {
        mBaiduMap.clear();

        ProjectResultBean result = null;
        for (ProjectResultBean bean : resultBeans) {
            if (null != position && !TextUtils.isEmpty(bean.getLat()) && !TextUtils.isEmpty(bean.getLng())) {
                double lat = Double.parseDouble(bean.getLat());
                double lng = Double.parseDouble(bean.getLng());
                if (position.latitude == lat && position.longitude == lng) {
                    result = bean;
                }
            }
            int res;
            switch (Integer.parseInt(bean.getSwitchType())) {
                case Const.JKQ:
                case Const.JKQ_4G:
                case Const.JKQ_PLE:
                    if (bean.getAlarmStatus().equals("0")) {
                        if (bean.getReturnValue().equals("0")) {
                            res = R.drawable.ic_jikongqi_lv;
                        } else {
                            res = R.drawable.ic_jikongqi_lan;
                        }
                    }else {
                        switch (bean.getAlarmLevel()){
                            case "0":
                                res = R.drawable.ic_jikongqi_huang;
                                break;
                            case "1":
                                res=R.drawable.ic_jikongqi_cheng;
                                break;
                            case "2":
                                res = R.drawable.ic_jikongqi_red;
                                break;
                            default:
                                res = R.drawable.ic_jikongqi_lv;
                                break;
                        }
                    }
                    break;
                default:
                    res = R.drawable.ic_location_now;
                    break;
            }
            if (!TextUtils.isEmpty(bean.getLat()) && !TextUtils.isEmpty(bean.getLng())) {
                if (bean.getLat().contains(",") || bean.getLng().contains(",")) {
                    LogUtil.e(TAG, bean.toString());
                } else {
                    LatLng point = new LatLng(Double.parseDouble(bean.getLat()), Double.parseDouble(bean.getLng()));
                    BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(res);

                    OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
                    mBaiduMap.addOverlay(option);
                }
            }
        }
        return result;
    }

    @Override
    public void showPop(LampBean lampBean) {
        int type = Integer.parseInt(lampBean.getSwitchType());
        switch (type) {
            case Const.JKQ:
            case Const.JKQ_4G:
            case Const.JKQ_PLE:
                showJkqPop(lampBean);
                break;
//            case Const.NB_SINGLE:
//            case Const.NB_DOUBLE:
//                showDanDengPop(lampBean);
//                break;
            default:
                showDanDengPop(lampBean);
                break;
        }
    }

    @Override
    public void changeMode(int type, String switchType) {
        switch (Integer.parseInt(switchType)) {
            case Const.JKQ:
            case Const.JKQ_4G:
            case Const.JKQ_PLE:
                if (null != mPopJkq)
                    mPopJkq.changeMode(type);
                break;
            case Const.NB_SINGLE:
            case Const.NB_DOUBLE:
                if (null != mPopDandeng)
                    mPopDandeng.changeMode(type);
                break;
            default:

                break;
        }

    }

    @Override
    public void openCloseOk(boolean open, String switchType) {
        switch (Integer.parseInt(switchType)) {
            case Const.JKQ:
            case Const.JKQ_4G:
            case Const.JKQ_PLE:
                if (null != mPopJkq)
                    mPopJkq.changeTdBtn(open);
                break;
            case Const.NB_SINGLE:
            case Const.NB_DOUBLE:
//                if (null != mPopDandeng)
//                    mPopDandeng.changeTdBtn(open);
                break;
            default:

                break;
        }
    }

    @Override
    public void showWarningData(WarningBean warningBean) {
        if (warningBean.getAllCount()==0){
            mLLGz.setVisibility(View.GONE);
        }else {
            mLLGz.setVisibility(View.VISIBLE);
            mTvYichangNum.setText(warningBean.getAllCount()>99?99+"+":warningBean.getAllCount()+"");
        }
    }

    @OnClick({R.id.ll_gz, R.id.ll_sao, R.id.ll_switch_project, R.id.tv_search})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.ll_gz:
                start(ProjectDetailFragment.newInstance("项目详情", "", ProjectDetailFragment.FROM_HOME));
                break;
            case R.id.ll_sao:
                requestCameraPermission();
                break;
            case R.id.tv_search:
                start(SearchFragment.newInstance(mId));
                break;
            case R.id.ll_switch_project:
                DeviceListDialogFragment fragment = DeviceListDialogFragment.newInstance();
                fragment.setOnDestroyListener(new BaseDialogFragment.OnDestroyListener() {
                    @Override
                    public void onDestroy(Object object, boolean isChange) {
                        if (null == object) {
                            return;
                        }
                        ProjectListBean bean = (ProjectListBean) object;
                        mId = bean.getId();
                        mPresenter.requestByProjectAndKeyWord(mId);
                        mPresenter.requestWarning(mId);
                    }
                });
                fragment.showDialog(getChildFragmentManager());
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void searchBack(SearchBackEvent event) {
        ProjectResultBean info = event.getInfo();
        double lat = Double.parseDouble(info.getLat());
        double lng = Double.parseDouble(info.getLng());
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(new LatLng(lat, lng)));
    }

    @Override
    protected void openCamera() {
        start(ScanFragment.newInstance(false));
    }

    private void start(BaseFragment fragment) {
        getParentDelegate().start(fragment);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        stateBar(true);
        if (null != mMapView) {
            mMapView.onResume();
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        stateBar(false);

        popupDismiss(mPopJkq);
        popupDismiss(mPopDandeng);

        if (null != mMapView) {
            mMapView.onPause();
        }
    }

    @Override
    public void onDestroy() {
        if (null != mMapView) {
            mMapView.onDestroy();
            mMapView = null;
        }
        EventBusUtils.unregister(this);
        super.onDestroy();
    }

    private void showJkqPop(LampBean bean) {
        popupDismiss(mPopDandeng);
        if (null == mPopJkq)
            mPopJkq = new JkqPop(getProxyActivity());
        mPopJkq.bindData(bean);
        mPopJkq.setClickListener(new OnItemClick<Object>() {
            @Override
            public void onClick(Object info, int tag) {
                List<String> codeList = (List<String>) info;
                if (tag == 2 || tag == 3) {
                    mPresenter.openClose(codeList, tag == 2 ? "0" : "1", bean.getSwitchType());
                }else if (tag==4){
                    List<LampBean> beans=new ArrayList<>();
                    bean.setCheck(true);
                    beans.add(bean);
                    showDialog(KgsjDialogFragment.newInstance(bean.getSwitchType(),beans));
                }else {
                    mPresenter.changeMode(codeList, tag, bean.getSwitchType());
                }
            }
        });
        showPop(mPopJkq);
    }

    private void showDialog(BaseDialogFragment fragment) {
        fragment.showDialog(getChildFragmentManager());
        fragment.setOnDestroyListener(new BaseDialogFragment.OnDestroyListener() {
            @Override
            public void onDestroy(Object object, boolean isChange) {

            }
        });
    }

    public void singleDialog(List<String> codeList, int tag, String switchType) {
        final String data[] = {"主灯", "辅灯", "主灯辅灯"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext())

                .setTitle("请选择你想操作的灯")

                .setSingleChoiceItems(data, -1, (dialogInterface, i) -> {
                    switch (i) {
                        case 0:
                            mPresenter.openCloseNbDouble(codeList, "1", tag == 2 ? "0" : "1", switchType);
                            break;
                        case 1:
                            mPresenter.openCloseNbDouble(codeList, "2", tag == 2 ? "0" : "1", switchType);
                            break;
                        case 2:
                            mPresenter.openCloseNbDouble(codeList, "3", tag == 2 ? "0" : "1", switchType);
                            break;
                        default:
                            showMsg("请选择你想操作的灯");
                            break;
                    }

                    dialogInterface.dismiss();
                });
        builder.show();
    }

    private void showDanDengPop(LampBean bean) {
        popupDismiss(mPopJkq);
        if (null == mPopDandeng)
            mPopDandeng = new DandengPop(getProxyActivity());
        mPopDandeng.bindData(bean);
        mPopDandeng.setClickListener(new OnItemClick<Object>() {
            @Override
            public void onClick(Object info, int tag) {
                LampBean bean = (LampBean) info;
                List<String> codeList = new ArrayList<>();
                codeList.add(bean.getCode());
                if (tag == 1 || tag == 2) {
                    if (Integer.parseInt(bean.getSwitchType()) == Const.NB_SINGLE) {
                        NormalDialog dialog = new NormalDialog(getContext());
                        dialog.content("是否打开或者关闭灯?")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("温馨提示")
                                .btnNum(2)
                                .btnTextColor(
                                        R.color.c_666666, R.color.c_666666
                                )
                                .btnText("是", "否")
                                .titleTextSize(23f)
                                .show();
                        dialog.setOnBtnClickL((OnBtnClickL) () -> {
                                    dialog.dismiss();
                                    mPresenter.openClose(codeList, tag == 2 ? "0" : "1", bean.getSwitchType());
                                },
                                (OnBtnClickL) () ->
                                        dialog.dismiss()
                        );

                    } else {
                        singleDialog(codeList, tag, bean.getSwitchType());
                    }
                } else if (tag == 3) {
                    HDimmerDialogFragment.newInstance(bean.getSwitchType(), bean).showDialog(getChildFragmentManager());
                } else if (tag == 4) {
                    NormalDialog dialog = new NormalDialog(getContext());
                    dialog.content("是否对选中设备校准时间?")
                            .style(NormalDialog.STYLE_TWO)//
                            .title("温馨提示")
                            .btnNum(2)
                            .btnTextColor(
                                    R.color.c_666666, R.color.c_666666
                            )
                            .btnText("是", "否")
                            .titleTextSize(23f)
                            .show();
                    dialog.setOnBtnClickL((OnBtnClickL) () -> {
                                dialog.dismiss();
                                List<LampBean> data = new ArrayList<>();
                                data.add(bean);
                                mPresenter.requestTime(bean.getSwitchType(), data);
                            },
                            (OnBtnClickL) () ->
                                    dialog.dismiss()
                    );
                } else {
//                    if (bean.getSwitchType().equals(Const.NB_SINGLE)) {
                    NormalDialog dialog = new NormalDialog(getContext());
                    dialog.content("是否切换控制模式?")
                            .style(NormalDialog.STYLE_TWO)//
                            .title("温馨提示")
                            .btnNum(2)
                            .btnTextColor(
                                    R.color.c_666666, R.color.c_666666
                            )
                            .btnText("是", "否")
                            .titleTextSize(23f)
                            .show();
                    dialog.setOnBtnClickL((OnBtnClickL) () -> {
                                dialog.dismiss();
                                mPresenter.changeMode(codeList, tag == 5 ? 0 : 1, bean.getSwitchType());
                            },
                            (OnBtnClickL) () ->
                                    dialog.dismiss()
                    );
//                    }else {
//                       singleDialog(codeList,tag,bean.getSwitchType());
//                    }
                }
            }
        });
        showPop(mPopDandeng);
    }

    private void showPop(PopupWindow popupWindow) {
        popupWindow.showAsDropDown(mRoot,
                DimenUtils.dp2px(getProxyActivity(), 15),
                DimenUtils.dp2px(getProxyActivity(), 16));
    }

    private void popupDismiss(PopupWindow popupWindow) {
        if (null != popupWindow) {
            popupWindow.dismiss();
        }
    }

}
